#pragma once
#include "PSCAD_br_info.h"

int PSCAD_br_info::read()
{
    branchesData.setZero(0, 0);
    std::ifstream file(path);
    if (!file.is_open())
    {
        std::cerr << "无法打开文件" << std::endl;
        return 1;
    }

    // 定义变量
    std::string line;
    bool isBranchesSection = false;
    bool isVoltagesSection = false;

    // 读取文件内容
    while (getline(file, line))
    {
        // 检测是否进入BRANCHES部分
        if (line.find("BRANCHES:") != std::string::npos)
        {
            isBranchesSection = true;
            continue;
        }
        // 检测是否进入VOLTAGES部分
        if (line.find("VOLTAGES:") != std::string::npos)
        {
            isVoltagesSection = true;
            continue;
        }

        // 检测是否离开BRANCHES部分
        if (isBranchesSection && line.empty() || line == "TRANSFORMERS:" || line == "ENDPAGE")
        {
            isBranchesSection = false;
            break;
        }
        // 检测是否离开VOLTAGES部分
        if (isVoltagesSection && line.empty() || line == "BRANCHES:" || line == "ENDPAGE")
        {
            isVoltagesSection = false;
        }

        // 如果是BRANCHES部分，解析数据
        if (isBranchesSection)
        {
            std::istringstream iss(line);
            std::string id, branchType;
            int busFrom, busTo;
            double value1, value2;

            // 跳过空格
            iss >> busFrom >> busTo;
            branchesData.conservativeResize(branchesData.rows() + 1, 2);
            branchesData(branchesData.rows() - 1, 0) = busFrom;
            branchesData(branchesData.rows() - 1, 1) = busTo;
        }

        if (isVoltagesSection)
        {
            std::istringstream iss(line);
            std::string symbol;
            int bus;

            iss >> bus;

            size_t commentPos = line.find("//");
            std::string comment = line.substr(commentPos + 3); // "//后面还有一个空格"
            if (bus > 0)
            {
                // cout << bus - 1 << " " << comment << endl;
                Vmap[comment] = bus - 1;
                Vmap_vers[bus - 1] = comment;
            }
        }
    }

    // // 输出矩阵内容
    // std::cout << "Branches Data:" << std::endl
    //           << branchesData << std::endl;

    // 关闭文件
    file.close();

    return 0;
}

int PSCAD_br_info::generate_A()
{
    num_br = branchesData.rows();
    num_node = 0;
    A.setZero(0, 0);
    for (int i = 0; i < branchesData.rows() * branchesData.cols(); i++)
    {
        if (branchesData(i) > num_node)
            num_node = branchesData(i);
    }
    num_node++;
    A.setZero(num_node - 1, num_br);
    for (int i = 0; i < branchesData.rows(); i++)
    {
        if (branchesData(i, 0) != 0)
            A(branchesData(i, 0) - 1, i) = 1;
        if (branchesData(i, 1) != 0)
            A(branchesData(i, 1) - 1, i) = -1;
    }
}